#coding:utf-8
import os
import time
from common.FuyuanwaiConf import FuyuanwaiConf
from common.koufuApi import KoufuApi
from common.koufuShopApi import KoufuShopApi

__author__ = 'yangxianming'

from common.KoufuConf import KoufuConf
import json
import requests


def case():
    #初始化必要的参数
    api_list = ["efuli.coremng.welfarecard.product.create", "efuli.coremng.welfarecard.product.pagequery", "efuli.coremng.welfarecard.product.start",
                "efuli.appmng.welfarecard.order.place", "efuli.appmng.welfarecard.order.payment", "efuli.coremng.welfarecard.order.audit",
                "efuli.appmng.welfarecard.order.export"]
    fuyuanwaiConf = FuyuanwaiConf()
    url = fuyuanwaiConf.testCoreDomain + "/mngWeb/mng"
    script_name = os.path.basename(__file__)
    tf = True
    test_result = ""

    try:
        #核心后管创建卡模板
        # name = str(int(time.time() * 1000))[4:]
        # body = {"request_id":1578883215370,"productName":name,"cardName":name,"logoIcon":"https://efulidev.oss-cn-hangzhou.aliyuncs.com/WELFARECARD_LOGO_ICON1578883195592.jpeg?Expires=1894243205&OSSAccessKeyId=LTAIEMcpIL4BsY0e&Signature=ZSMEDrxU31c94FLiWVU7SqRjJEs%3D","bgPicture":"https://efulidev.oss-cn-hangzhou.aliyuncs.com/WELFARECARD_BG_PICTURE1578883195592.png?Expires=1894243210&OSSAccessKeyId=LTAIEMcpIL4BsY0e&Signature=25vEFX0m169620dpdP0%2Fb%2FuJ4vk%3D","usageScenarios":"3d67ee21bec04b3cac2da2a84ee5db74,cbc278c5af4c498990d16a167630acaa,ba2c2dca637b47fead1a8d30e5357100,13e672bcc4c34b0c9cc4bb4b7ed153d1,1b949411f92f4c0882ca9bf99aa07904,f7dece3f1283430cb1740815bae18575,8ade8a0babdf486f84f401b0260d37fe","apps":"38ecf881d0374b0aaa6eab4717a07b32,d15ff1a1fc944612829a8c9427fdf066,460655499def451883d79eb6117cd623,460655499def451883d79eb6117cd6df,yibai1a1fc944612829a8c9427fdf032,welfarepoint12345678901234567890,9d1204f8211a424aa881ed838e3895b4,dingwangfc944612829a8c9427fdf032,guanaitong944612829a8c9427fdf032,duoyoucaic944612829a8c9427fdf032,ceshi1a1fc944612829a8c9427fdf032,shopmall432112345678901234567890,009b364a487c4e8ead557a02a76c53ba,4dcedbe6f58b4e3e87b070655041778f,3220882cec6e4a8a95cddf940d79a35e,198123441ecf4056aa8d11114fac7de8,7e4e4b7d5fad4a02a2923fd586be241b","roleToken":"67dfe9cfa5d01d92421814e1832691e8"}
        # p ={"action":api_list[0],"body":body}
        # r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCoreHeader)
        # r_json = r.json()
        # print("这个是接口" + api_list[0] + "返回的全部参数\n", r_json)
        # print("卡名称为 " + name + " 的模板已经被成功创建\n")

        #查询productId
        # product_id = ""
        # body = {"request_id":1578884328076,"searchId":"","cardName":"","pageNum":1,"pageSize":10,"roleToken":"67dfe9cfa5d01d92421814e1832691e8"}
        # p ={"action":api_list[1],"body":body}
        # r_json = {}
        # while True:
        #     need_break = False
        #     r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCoreHeader)
        #     r_json = r.json()
        #     card_list = r_json["return_data"]["list"]
        #     for oneCard in card_list:
        #         # print(oneCard["cardName"])
        #         if oneCard["cardName"] == name:
        #             product_id = oneCard["productId"]
        #             need_break = True
        #             break
        #     if  need_break:
        #         break
        # # print("这个是接口" + api_list[1] + "返回的全部参数\n", r_json)
        # print("这个是接口product_id", product_id)


        # When families gather for Christmas dinner, some will stick to formal traditions dating
        # back to Grandma's generation.Their table will be set with the good dishes and silver, and
        # the dress code will be Sunday-best

        # But in many other home, this china-and-silver elegance has given way to a stoneware-and-stainless informality, with dresses assuming an equally casual-Friday look.
        # For hosts and guests, the change means greater simplicity and comfort. For makers of fine china in Britain,it spells economic hard times.

        # Last week Royal Doulton, the largest employer in Stoke-on-Trent, announced that it is
        # eliminating 1000 jobs - one-fifth of its total workforce, That brings to more than 4000 the
        # number of position lost in 18 months in the pottery region. Wedgwood and other pottery
        # factories made cuts earlier.

        # Although a stong pound and weak markets in Asia play a role in the downsizing, the
        # layoffs in Stoke have their roots in earthshaking social shifts. A spokesman for Royal Doulton
        # admitted  that the company "has been somewhat slow in catching up with the trend" toward
        # casual dining. Families eat together less often, he explained, and more people eat alone, either
        # because they are single or they eat in front of television. Even dinner parties, if they happen at
        # all, have one casual. In a time of long work hours and demanding family schedules, busy hosts
        # insist, rightly, that it's better to share a takeout pizza on paper plates in the family room than to
        # wait for the perfect moment or a "real" dinner party. Too often, the perfect moment never comes.
        # Iron a fine-patterned tablecloth? Forget it. Polish the silver? Who has time?

        # Yet the loss of formality has its down side. The fine points of etiquette that children
        # might once have learned at the table by observation or instruction from parents and
        # grandparents ("Chew with your mouth closed","Keep your elbows off the table") must be
        # picked up elsewhere. Some companies now offer etiquette seminars for employees who may be
        # competent professionally but clueless socially.



        #启用创建的卡模板
        # body = {"request_id":1578884125666,"productId":product_id,"roleToken":"67dfe9cfa5d01d92421814e1832691e8"}
        # p ={"action":api_list[2],"body":body}
        # r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCoreHeader)
        # r_json = r.json()
        # print("这个是接口" + api_list[2] + "返回的全部参数\n", r_json)

        ###########################################

        #企业后管下单
        name = "967897489"
        product_id = "8c7f995e21e245c99b68e430e6b54375"
        corp_name = "大明有限公司	"
        corp_id = "1a409a710e1640998178f970c4872504"
        body = {"request_id":1578887086579,"orders":{"orders":[{"corpName":corp_name,"corpId":corp_id,"items":[{"request_id":1578887071617,"logoIcon":"https://oalipay-dl-django.alicdn.com/rest/1.0/image?fileIds=k1a-vP1hTdCKzC7y80qnpAAAACMAAQED&zoom=original","bgPicture":"https://oalipay-dl-django.alicdn.com/rest/1.0/image?fileIds=GFHoWWZWSZ-Jbe-umCojwgAAACMAAQED&zoom=original","cardName":name,"productId":product_id,"quantity":"3","faceValue":200,"okNo":True}]}]},"roleToken":"399df235cb5f99511a6b3cb042ccc6b8"}
        p = {"action":api_list[3], "body":body}
        r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCorpHeader)
        print(r.content)
        r_json = r.json()
        order_id = r_json["return_data"]["orders"][0]["orderId"]
        print("这个是接口" + api_list[3] + "返回的全部参数\n", r_json)
        print("获取了order_id:", order_id)

        #企业后管提交订单
        body = {"request_id":1578902365890,"orderId":order_id,"roleToken":"35fb15a69e4487c2100e3f524b2a9c41"}
        p = {"action":api_list[4], "body":body}
        r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCorpHeader)
        r_json = r.json()
        print("这个是接口" + api_list[4] + "返回的全部参数\n", r_json)

        #核心后管审核通过
        body = {"request_id":1578902607423,"orderId":order_id,"appId":"welfarepoint12345678901234567890","backRemark":"","roleToken":"a8e1e6de4acbaca52a4e0309e9c288a1"}
        p = {"action":api_list[5], "body":body}
        r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCoreHeader)
        r_json = r.json()
        print("这个是接口" + api_list[5] + "返回的全部参数\n", r_json)

        #企业后管第一次导出（设置导出信息，卡券有效期等信息）
        body = {"request_id":1578903323717,"orderId":order_id,"validityPeriodType":"1","relativeDuration":"1","relativeTimeUnit":"DAY","cardRelativeTimeUnit":"DAY","cardRelativeDuration":"1","genShortLink":"Y","genAliToken":"N","roleToken":"35fb15a69e4487c2100e3f524b2a9c41"}
        p = {"action":api_list[6], "body":body}
        r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCorpHeader)
        r_json = r.json()
        print("这个是接口" + api_list[6] + "返回的全部参数\n", r_json)

        time.sleep(3)

        #企业后管第二次导出（拿到下载地址）
        body = {"request_id":1578903323717,"orderId":order_id,"validityPeriodType":"1","relativeDuration":"1","relativeTimeUnit":"DAY","cardRelativeTimeUnit":"DAY","cardRelativeDuration":"1","genShortLink":"Y","genAliToken":"N","roleToken":"35fb15a69e4487c2100e3f524b2a9c41"}
        p = {"action":api_list[6], "body":body}
        r = requests.post(url, data=json.dumps(p), headers=fuyuanwaiConf.testCorpHeader)
        r_json = r.json()
        u = r_json["return_data"]["fileOssUrl"]
        print("这个是接口" + api_list[6] + "返回的全部参数\n", r_json)

        #请求导出地址并获取短链接
        # u = "https://efulidev.oss-cn-hangzhou.aliyuncs.com/welfarecard_order_export_664f48b34db040928f04537d27467711.csv?Expires=1894263326&OSSAccessKeyId=LTAIEMcpIL4BsY0e&Signature=6oODaOMxCLVVRCA5H%2F52WwvY%2Br0%3D"
        r = requests.get(u).content.decode('utf-8')
        short_link1 = r.split("\n")[7].split(",")[8]
        short_link2 = r.split("\n")[8].split(",")[8]
        short_link3 = r.split("\n")[9].split(",")[8]
        print("下载链接：", short_link1, short_link2, short_link3)

        #发送钉钉机群，余下的操作需要收到在支付宝操作
        # https://oapi.dingtalk.com/robot/send?access_token=bc9791ba2f884d34842c71148bff1fdc855e647f20f0cdbfc9454c0015ee1f8b
        d_alert_url = "https://oapi.dingtalk.com/robot/send?access_token=bc9791ba2f884d34842c71148bff1fdc855e647f20f0cdbfc9454c0015ee1f8b"
        t = "[mu]下面链接为测试环境新建卡模板完成采购支付后导出的短链接，请复制其中一条在支付宝中做粘贴操作并验证知否可以正常买单"
        p = {"msgtype":"text","text":{"content":t},"at":{"atMobiles":[],"isAtAll":False}}
        requests.post(d_alert_url, data=json.dumps(p), headers=fuyuanwaiConf.dd_alert_header)
        time.sleep(1)
        for one in [short_link1, short_link2, short_link3]:
            p = {"msgtype":"text","text":{"content":"[mu]"+one},"at":{"atMobiles":[],"isAtAll":False}}
            r = requests.post(d_alert_url, data=json.dumps(p), headers=fuyuanwaiConf.dd_alert_header)
            print(r.content)
            time.sleep(1)

        #具体判断
        # if voucherId is not None:
        #     tf = False
    except Exception as e:
        err_info = str(e).replace("'", "").replace("\"", "")
        test_result = "非预期的异常,脚本文件:" + script_name + "; 错误信息：" + err_info
        tf = -2

    #定义预期描述
    print(str(tf))
    print(test_result)
    expect_result = "返回参数ebuyCode是否是空"

    #返回测试结果 第一个参数:True or False    第二个参数测试结果描述
    return tf, [test_result, expect_result]

case()